<template>
  <el-dialog :model-value="props.show" :title="`${title + levelStr}标签`" width="440px" :before-close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item :label="`${levelStr}标签名称`" prop="name">
        <el-input style="width: 80%;" v-model="form.name" placeholder="请输入"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="loading" @click="handleClose">取消</el-button>
        <el-button :loading="loading" type="primary" @click="confirm(formRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { useTableRefresh } from '@/hooks';
import { useLabelManagement } from '../Hooks';
import { saveMemberTag } from '@/api/Member/index'

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  detail: {
    type: Object,
    default: () => { },
  },
})
const { seachTableRef } = useLabelManagement()

const level = computed(() => {
  if (props.isEdit) {
    return props.detail.parentId === '0' ? 1 : 2;
  } else {
    return Object.keys(props.detail).length > 0 ? 2 : 1;
  }
});
const levelStr = computed(() => {
  return level.value === 1 ? '一级' : '二级';
});
const title = computed(() => {
  return props.isEdit ? '编辑' : '新增';
});

const rules = ref({
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
  ],
});
const form = ref({
  name: '',
});
watch(()=>props.detail,()=>{
  if(props.isEdit){
    form.value.name = props.detail?.labelName ?? '';
  }
})

const loading = ref(false);
const formRef = ref();
const confirm = async (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    try{
      if (!valid) return;
      loading.value = true;
      const params = {
        labelName: form.value.name,
      };
      if (props.isEdit) {
        params.id = props.detail.id;
        params.parentId = props.detail.parentId;
      }
      if(!props.isEdit && level.value === 2){
        params.parentId = props.detail.id;
      }
      console.log(params);
      await saveMemberTag(params)
      handleClose();
      ElMessage.success(`${title.value}${levelStr.value}标签成功`);
      useTableRefresh(seachTableRef,props.isEdit)
    }finally{
      loading.value = false;
    }
    
  });

}

const emit = defineEmits(['close']);
const resetForm = () => {
  formRef.value?.resetFields();
};
const handleClose = () => {
  resetForm();
  emit('close', false);
};
</script>

<style lang="less" scoped></style>